<?php

declare(strict_types=1);

namespace App\Middleware;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class JwtMiddleware implements MiddlewareInterface
{
    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response = $response;
        $this->pathInfo = $request->getPathInfo();
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $pathInfo = $this->pathInfo;
        if (strpos($pathInfo, '/admin') === false) {
            if (!auth('jwt')->check()) {
                return $this->response->json(
                    [
                        'status' => 401,
                        'message' => 'token已失效',
                        'data' => [],
                    ]
                );
            }
        } else {
            if (!auth('manager')->check()) {
                return $this->response->json(
                    [
                        'status' => 401,
                        'message' => 'token已失效',
                        'data' => [],
                    ]
                );
            }
        }

        return $handler->handle($request);
    }
}
